package cn.miju.ser.alipay.service;

import cn.miju.alipay.model.PayResultNotifyRequest;
import cn.miju.database.constant.DbConstant;
import cn.miju.database.entity.Merchant;
import cn.miju.database.entity.PayOrder;
import cn.miju.database.service.MerchantDataService;
import cn.miju.database.service.PayOrderDataService;
import cn.miju.ser.alipay.constant.AlipayConstant;
import cn.miju.ser.common.rocketmq.Topic;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

/**
 * <pre>
 * 支付宝支付回调接口实现
 * </pre>
 *
 * @author zhuming
 * @version 1.0.0
 * @since 2023-03-10 14:47
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AlipayCallbackServiceImpl implements AlipayCallbackService {

    private final PayOrderDataService payOrderDataService;
    private final MerchantDataService merchantDataService;
    private final RocketMQTemplate rocketMQTemplate;

    /**
     * 支付结果回调通知
     *
     * @param request 入参
     */
    @Async
    @Override
    public void payCallbackNotify(PayResultNotifyRequest request) {
        PayOrder payOrder = payOrderDataService.getOne(new LambdaQueryWrapper<PayOrder>().
                eq(PayOrder::getPlatTradeNo, request.getOutTradeNo()).
                in(PayOrder::getStatus, DbConstant.PayOrderStatus.WAITING, DbConstant.PayOrderStatus.TIMEOUT));
        if (Objects.isNull(payOrder)) {
            log.error("回调通知订单{}不存在!", request.getOutTradeNo());
            return;
        }
        String tradeStatus;
        if (AlipayConstant.TRADESTATUS_SUCCESS.getCode().equals(request.getTradeStatus())) {
            tradeStatus = DbConstant.PayOrderStatus.SUCCESS;
        } else if (AlipayConstant.TRADESTATUS_WAIT_PAY.getCode().equals(request.getTradeStatus())) {
            tradeStatus = DbConstant.PayOrderStatus.WAITING;
        } else if (AlipayConstant.TRADESTATUS_CLOSE.getCode().equals(request.getTradeStatus())) {
            tradeStatus = DbConstant.PayOrderStatus.ALL_REFUND;
        } else {
            tradeStatus = DbConstant.PayOrderStatus.FAIL;
        }
        payOrder.setStatus(tradeStatus);
        payOrder.setTradeNo(request.getTradeNo());
        payOrder.setPayOrderTime(LocalDateTime.parse(request.getGmtPayment(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        payOrder.setUpdatedTime(LocalDateTime.now());
        payOrderDataService.updateById(payOrder);
        // 通知接入方
        Merchant merchant = merchantDataService.getById(payOrder.getMerchantId());
        if (StringUtils.isNotBlank(merchant.getPayNotifyUrl())) {
            rocketMQTemplate.syncSend(Topic.PAY_RESULT_NOTIFY_TOPIC, MessageBuilder.withPayload(payOrder.getId()).build(), 3000);
        }
    }
}
